#include "Engine/AuxTypesDX9.h"
#include "IAInterfaceDX9.h"

CIAInterfaceDX9::CIAInterfaceDX9( )
{
    m_pIndexBuffer = NULL;
}

CIAInterfaceDX9::~CIAInterfaceDX9( )
{
    SAFE_RELEASE(m_pIndexBuffer);
    for (size_t i = 0; i < m_VertexBuffers.size(); i++)
    {
        SAFE_RELEASE(m_VertexBuffers[i]);
    }
}

mBool CIAInterfaceDX9::CreateIndexBuffer( mVoid *a_pBufData, mUInt a_uBufSize, TVariableType a_IndexType )
{
    mVoid *pIndices;
    D3DFORMAT Fmt;
    if (a_IndexType == TUINT32)
        Fmt = D3DFMT_INDEX32;
    if (a_IndexType == TUINT16)
        Fmt = D3DFMT_INDEX16;
    g_D3DDevice.pD3D9Device->CreateIndexBuffer(a_uBufSize, 
        D3DUSAGE_WRITEONLY, 
        Fmt, 
        D3DPOOL_DEFAULT, 
        &m_pIndexBuffer,
        NULL);
    m_pIndexBuffer->Lock(0, 0, (void**)&pIndices, 0);
    memcpy_s(pIndices, a_uBufSize, a_pBufData, a_uBufSize);
    m_pIndexBuffer->Unlock();

    return true;
}

mUInt CIAInterfaceDX9::CreateVertexBuffer( mVoid *a_pBufData, mUInt a_uBufSize, mUInt a_uStride )
{
    IDirect3DVertexBuffer9 *pBuf;
    g_D3DDevice.pD3D9Device->CreateVertexBuffer(a_uBufSize,
        D3DUSAGE_WRITEONLY,
        0,
        D3DPOOL_DEFAULT,
        &pBuf,
        0);

    if (pBuf == NULL)
        return false;

    mVoid *pVertices;
    pBuf->Lock(0, 0, (void**)&pVertices, 0);
    memcpy_s(pVertices, a_uBufSize, a_pBufData, a_uBufSize);
    pBuf->Unlock();

    m_VertexBuffers.push_back(pBuf);
    m_Strides.push_back(a_uStride);
    return m_VertexBuffers.size() - 1;
}

mVoid CIAInterfaceDX9::IASetupBuffers( )
{
    if (m_pIndexBuffer)
        g_D3DDevice.pD3D9Device->SetIndices(m_pIndexBuffer);

    for (size_t i = 0; i < m_VertexBuffers.size(); i++)
    {
        g_D3DDevice.pD3D9Device->SetStreamSource(i, m_VertexBuffers[i], 0, m_Strides[i]);
    }
}